<template>
  <view class="settings-page">
    <view class="page-header">
      <u-navbar
        title="设置"
        :autoBack="true"
        bgColor="#fff"
      />
    </view>
    
    <view class="settings-content">
      <!-- 个人信息设置 -->
      <view class="settings-section">
        <view class="section-title">个人信息</view>
        <view class="settings-list">
          <view class="setting-item" @click="editAvatar">
            <text class="setting-label">头像</text>
            <view class="setting-value">
              <image :src="safeUserInfo.avatar || '/static/icons/default-avatar.png'" class="avatar" />
              <u-icon name="arrow-right" color="#999" size="24" />
            </view>
          </view>
          
          <view class="setting-item" @click="editNickname">
            <text class="setting-label">昵称</text>
            <view class="setting-value">
              <text class="value-text">{{ safeUserInfo.nickname || '未设置' }}</text>
              <u-icon name="arrow-right" color="#999" size="24" />
            </view>
          </view>
          
          <view class="setting-item" @click="editBio">
            <text class="setting-label">个性签名</text>
            <view class="setting-value">
              <text class="value-text">{{ safeUserInfo.bio || '未设置' }}</text>
              <u-icon name="arrow-right" color="#999" size="24" />
            </view>
          </view>
        </view>
      </view>
      
      <!-- 伴侣信息设置 -->
      <view class="settings-section">
        <view class="section-title">伴侣信息</view>
        <view class="settings-list">
          <view class="setting-item" @click="bindPartner">
            <text class="setting-label">绑定伴侣</text>
            <view class="setting-value">
              <text v-if="safeUserInfo.partner" class="value-text">{{ safeUserInfo.partner.nickname }}</text>
              <text v-else class="value-text">未绑定</text>
              <u-icon name="arrow-right" color="#999" size="24" />
            </view>
          </view>
          
          <view v-if="safeUserInfo.partner" class="setting-item" @click="unbindPartner">
            <text class="setting-label">解除绑定</text>
            <view class="setting-value">
              <u-icon name="arrow-right" color="#999" size="24" />
            </view>
          </view>
        </view>
      </view>
      
      <!-- 通知设置 -->
      <view class="settings-section">
        <view class="section-title">通知设置</view>
        <view class="settings-list">
          <view class="setting-item">
            <text class="setting-label">订单通知</text>
            <u-switch v-model="settings.orderNotification" @change="updateNotificationSettings" />
          </view>
          
          <view class="setting-item">
            <text class="setting-label">积分提醒</text>
            <u-switch v-model="settings.pointsNotification" @change="updateNotificationSettings" />
          </view>
          
          <view class="setting-item">
            <text class="setting-label">活动推送</text>
            <u-switch v-model="settings.activityNotification" @change="updateNotificationSettings" />
          </view>
        </view>
      </view>
      
      <!-- 其他设置 -->
      <view class="settings-section">
        <view class="section-title">其他设置</view>
        <view class="settings-list">
          <view class="setting-item" @click="clearCache">
            <text class="setting-label">清除缓存</text>
            <view class="setting-value">
              <text class="value-text">{{ cacheSize }}</text>
              <u-icon name="arrow-right" color="#999" size="24" />
            </view>
          </view>
          
          <view class="setting-item" @click="checkUpdate">
            <text class="setting-label">检查更新</text>
            <view class="setting-value">
              <text v-if="hasUpdate" class="value-text update-available">有新版本</text>
              <text v-else class="value-text">已是最新版本</text>
              <u-icon name="arrow-right" color="#999" size="24" />
            </view>
          </view>
          
          <view class="setting-item" @click="aboutUs">
            <text class="setting-label">关于我们</text>
            <view class="setting-value">
              <u-icon name="arrow-right" color="#999" size="24" />
            </view>
          </view>
        </view>
      </view>
      
      <!-- 退出登录 -->
      <view class="logout-section">
        <custom-button
          text="退出登录"
          type="secondary"
          size="large"
          @click="handleLogout"
        />
      </view>
    </view>
    
    <!-- 编辑弹窗 -->
    <modal
      :show="showEditModal"
      :title="editModalTitle"
      :show-footer="true"
      @close="closeEditModal"
      @confirm="saveEdit"
    >
      <view class="edit-form">
        <u-input
          v-model="editValue"
          :placeholder="editPlaceholder"
          :maxlength="editMaxLength"
          border="surround"
        />
      </view>
    </modal>
  </view>
</template>

<script>
import { mapState, mapActions } from 'pinia'
import { useUserStore } from '@/store/modules/user'
import CustomButton from '@/components/custom-button/index.vue'
import Modal from '@/components/modal/index.vue'

export default {
  name: 'Settings',
  components: {
    CustomButton,
    Modal
  },
  data() {
    return {
      settings: {
        orderNotification: true,
        pointsNotification: true,
        activityNotification: true
      },
      cacheSize: '0KB',
      hasUpdate: false,
      showEditModal: false,
      editModalTitle: '',
      editValue: '',
      editField: '',
      editPlaceholder: '',
      editMaxLength: 50
    }
  },
  computed: {
    ...mapState(useUserStore, ['userInfo']),
    safeUserInfo() {
      return this.userInfo || {}
    }
  },
  mounted() {
    this.loadSettings()
    this.calculateCacheSize()
  },
  methods: {
    ...mapActions(useUserStore, ['updateUserInfo', 'logout']),
    
    loadSettings() {
      // 从本地存储加载设置
      const saved = uni.getStorageSync('userSettings')
      if (saved) {
        this.settings = { ...this.settings, ...saved }
      }
    },
    
    updateNotificationSettings() {
      uni.setStorageSync('userSettings', this.settings)
      uni.showToast({ title: '设置已保存', icon: 'success' })
    },
    
    calculateCacheSize() {
      // 计算缓存大小
      this.cacheSize = '2.3MB' // 模拟值
    },
    
    editAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          // 上传头像
          uni.showLoading({ title: '上传中...' })
          setTimeout(() => {
            uni.hideLoading()
            this.updateUserInfo({ avatar: res.tempFilePaths[0] })
            uni.showToast({ title: '头像更新成功', icon: 'success' })
          }, 1000)
        }
      })
    },
    
    editNickname() {
      this.editModalTitle = '修改昵称'
      this.editField = 'nickname'
      this.editValue = this.userInfo.nickname || ''
      this.editPlaceholder = '请输入昵称'
      this.editMaxLength = 20
      this.showEditModal = true
    },
    
    editBio() {
      this.editModalTitle = '修改个性签名'
      this.editField = 'bio'
      this.editValue = this.userInfo.bio || ''
      this.editPlaceholder = '请输入个性签名'
      this.editMaxLength = 100
      this.showEditModal = true
    },
    
    closeEditModal() {
      this.showEditModal = false
      this.editValue = ''
    },
    
    saveEdit() {
      if (!this.editValue.trim()) {
        uni.showToast({ title: '内容不能为空', icon: 'none' })
        return
      }
      
      this.updateUserInfo({ [this.editField]: this.editValue.trim() })
      this.closeEditModal()
      uni.showToast({ title: '修改成功', icon: 'success' })
    },
    
    bindPartner() {
      uni.showModal({
        title: '绑定伴侣',
        content: '请输入伴侣的邀请码',
        editable: true,
        placeholderText: '邀请码',
        success: (res) => {
          if (res.confirm && res.content) {
            uni.showLoading({ title: '绑定中...' })
            setTimeout(() => {
              uni.hideLoading()
              // 模拟绑定成功
              this.updateUserInfo({
                partner: {
                  id: 2,
                  nickname: '小可爱',
                  avatar: '/static/icons/partner-avatar.png'
                }
              })
              uni.showToast({ title: '绑定成功', icon: 'success' })
            }, 1000)
          }
        }
      })
    },
    
    unbindPartner() {
      uni.showModal({
        title: '解除绑定',
        content: '确定要解除与伴侣的绑定吗？',
        success: (res) => {
          if (res.confirm) {
            this.updateUserInfo({ partner: null })
            uni.showToast({ title: '已解除绑定', icon: 'success' })
          }
        }
      })
    },
    
    clearCache() {
      uni.showModal({
        title: '清除缓存',
        content: '确定要清除所有缓存吗？',
        success: (res) => {
          if (res.confirm) {
            uni.clearStorageSync()
            this.cacheSize = '0KB'
            uni.showToast({ title: '缓存已清除', icon: 'success' })
          }
        }
      })
    },
    
    checkUpdate() {
      uni.showLoading({ title: '检查中...' })
      setTimeout(() => {
        uni.hideLoading()
        this.hasUpdate = false // 模拟无更新
        uni.showToast({ title: '已是最新版本', icon: 'success' })
      }, 1000)
    },
    
    aboutUs() {
      uni.showModal({
        title: '关于我们',
        content: '小爱餐厅 - 情侣专属点餐系统\n\n版本：v1.0.0\n专为情侣打造的浪漫点餐体验',
        showCancel: false
      })
    },
    
    handleLogout() {
      uni.showModal({
        title: '退出登录',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            this.logout()
            uni.reLaunch({ url: '/pages/index/index' })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.settings-page {
  min-height: 1334rpx;
  background: #f5f5f5;
}

.page-header {
  :deep(.u-navbar) {
    border-bottom: 1rpx solid #f5f5f5;
}
}

.settings-content {
  padding: 24rpx;
}

.settings-section {
  margin-bottom: 40rpx;
}

.section-title {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 16rpx;
  padding-left: 16rpx;
}

.settings-list {
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
}

.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx;
  border-bottom: 1rpx solid #f5f5f5;
  
  &:last-child {
    border-bottom: none;
}
  
  &:active {
    background: #f8f8f8;
}
}

.setting-label {
  font-size: 30rpx;
  color: #333;
}

.setting-value {
  display: flex;
  align-items: center;
   margin-right: 16rpx; &:last-child { margin-right: 0; }
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
}

.value-text {
  font-size: 28rpx;
  color: #666;
  
  &.update-available {
    color: #ff4757;
}
}

.logout-section {
  margin-top: 80rpx;
  padding: 0 40rpx;
}

.edit-form {
  padding: 20rpx;
}
</style>